using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using System.IO;
using System.Web.UI;
using System.Web;

namespace JsonHTTPHandler.Formatter
{
  public class JsonFormatter
  {
    public static string WriteJSONObjectToHTML(string jsonObject)
    {
      StringWriter stringWriter = new StringWriter();
      HtmlTextWriter writer = new HtmlTextWriter(stringWriter);

      using (JsonReader reader = new JsonReader(new StringReader(jsonObject)))
      {
        while (reader.Read())
        {
          string token = reader.TokenType.ToString();
          string value = "";
          if (reader.Value != null)
          {
            value = reader.Value.ToString();
          }

          switch (reader.TokenType)
          {
            case JsonToken.StartArray:
              writer.Write("<ul><li>{0}</li><ul>", value == "" ? "Array Elements" : value);
              break;
            case JsonToken.StartObject:
              writer.Write("<ul><li>Object</li><ul>");
              break;

            case JsonToken.EndArray:
            case JsonToken.EndObject:
              writer.Write("</ul></ul>");
              break;

            case JsonToken.PropertyName:
              writer.Write("<li>{0}: ", value);
              break;

            case JsonToken.Boolean:
            case JsonToken.Constructor:
            case JsonToken.Date:
            case JsonToken.Float:
            case JsonToken.Integer:
            case JsonToken.None:
            case JsonToken.String:
            case JsonToken.Undefined:
              writer.Write("{0} ({1})</li>", value, token);
              break;

            case JsonToken.Null:
              writer.Write("{0}</li>", "null");
              break;

            case JsonToken.Comment:
              break;
          }
        }
      }

      writer.Flush();

      return stringWriter.ToString();
    }
  }
}
